package cn.fancy.sdk.login.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.QdRegisterCallback;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.LoginSwitchManage;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.QdLoginResult;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.Checker;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.pay.WebViewActivity;
import cn.fancy.sdk.utils.CheckLoginStateUtil;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import com.bytedance.applog.game.GameReportHelper;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;

public class RegisterAccountView extends BaseView {
    
    private IActivityManager activityMgr;
    private DBHelper dbHelper;
    private Activity ownerActivity;
    private SdkAsyncTask<String> registerAsyncTask = null;
    private Context mContext;
    private long lastTime = 0;
    private SdkAsyncTask<String> registerPhoneAsyncTask;
    private EditText bb_user_txt, bb_password_txt, bb_mobile_txt, bb_mess_code;
    private Timer timer;
    private Handler handler;
    private TextView registsure, mSendMess, guild_callcustom, guild_certification;
    private int save_intauthenticate = 0; // 保存注册完成之后返回的防成迷开关， 因为要给注册完成之后的登陆用
    private ImageView registcancle, et_eye;
    private String originalPassword;
    
    private LinearLayout ll_agreement;
    private CheckBox cb_agreement;
    private TextView link_agreement;
    private TextView tv_agreement;
    private boolean needCheckBox;
    
    public RegisterAccountView(Context context) {
        super(context);
    }
    
    public RegisterAccountView(Activity cActivity, IActivityManager activityMgr) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_registeraccount"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        dbHelper = DBHelper.getInstance(mContext);
        initView();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what > 0) {
                    mSendMess.setText(String.format("请%02d秒后重试", msg.what));
                } else {
                    mSendMess.setText("重新获取");
                    mSendMess.setEnabled(true);
                    timer.cancel();
                }
            }
        };
    }
    
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.postInvalidate();
        CommMessage.sifReturnLoginView = true;
    }
    
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        CommMessage.sifReturnLoginView = false;
    }
    
    private void initView() {
        mSendMess = (TextView) this.findViewById(ResUtil.getId(mContext,
            "bb_code_send"));
        mSendMess.setOnClickListener(this);
        mSendMess.setClickable(true);
        registsure = (TextView) this.findViewById(ResUtil.getId(mContext,
            "bb_register_confirm"));
        registsure.setOnClickListener(this);
        registcancle = (ImageView) this.findViewById(ResUtil.getId(mContext,
            "bb_register_cancle"));
        registcancle.setOnClickListener(this);
        bb_user_txt = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_account"));
        bb_user_txt.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        bb_user_txt.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
                String editable = bb_user_txt.getText().toString();
                String regEx = "[^a-zA-Z0-9]"; // 只能输入字母或数字
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim(); // 删掉不是字母或数字的字符
                if (!editable.equals(str)) {
                    bb_user_txt.setText(str); // 设置EditText的字符
                    bb_user_txt.setSelection(str.length()); // 因为删除了字符，要重写设置新的光标所在位置
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            }
            
            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        
        bb_password_txt = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_pass"));
        bb_password_txt.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD
            | InputType.TYPE_CLASS_TEXT);
        bb_password_txt.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        bb_password_txt.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
                String editable = bb_password_txt.getText().toString();
                String regEx = "[^a-zA-Z0-9]"; // 只能输入字母或数字
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim(); // 删掉不是字母或数字的字符
                if (!editable.equals(str)) {
                    bb_password_txt.setText(str); // 设置EditText的字符
                    bb_password_txt.setSelection(str.length()); // 因为删除了字符，要重写设置新的光标所在位置
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            }
            
            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        
        bb_mobile_txt = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_phone"));
        bb_mess_code = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_iden"));
        
        guild_callcustom = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_callcustom"));
        guild_certification = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_certification"));
        guild_callcustom.setOnClickListener(this);
        guild_certification.setOnClickListener(this);
        
        et_eye = (ImageView) this.findViewById(ResUtil
            .getId(mContext, "et_eye"));
        et_eye.setSelected(false);
        et_eye.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if (et_eye.isSelected()) {
                    et_eye.setSelected(false);
                    // eyeImg.setText("显示");
                    et_eye.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_off"));
                    bb_password_txt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    et_eye.setSelected(true);
                    et_eye.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_on"));
                    bb_password_txt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
    
        ll_agreement = (LinearLayout) this.findViewById(ResUtil.getId(mContext, "ll_agreement"));
        cb_agreement = (CheckBox) this.findViewById(ResUtil.getId(mContext, "cb_agreement"));
        link_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "link_agreement"));
        tv_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "tv_agreement"));
        needCheckBox = needCheckBoxAgreeMent();
    }
    
    //===================是否展示同意协议
    private static final String DAIMIAO = "daimiao";
    private static final String BA_YOU = "bayou";
    private static final String AGREEMENT_URL = "/mobile/float/game_agreement";
    
    private boolean needCheckBoxAgreeMent() {
        if (GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains(DAIMIAO) || GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains(BA_YOU)) {
            link_agreement.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    //跳h5
                    String url = GuildBaseInfo.getInstance().getMetaUrl("API_URL") + AGREEMENT_URL;
                    WebViewActivity.start(getContext(), url, "游戏服务协议");
                }
            });
            return true;
        } else {
            ll_agreement.setVisibility(GONE);
            return false;
        }
    }
    
    private boolean verifyCheckBox(){
        if(needCheckBox && !cb_agreement.isChecked()){
            Toast.makeText(getContext(), "请先确认已阅读《游戏服务协议》", Toast.LENGTH_LONG).show();
            tv_agreement.setTextColor(Color.parseColor("#FF0000"));
            return false;
        }
        return true;
    }
    //===================是否展示同意协议end
    
    @Override
    public void onClick(View v) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - lastTime < 1500) {
            lastTime = nowTime;
            return;
        }
        
        int vid = v.getId();
        if (vid == ResUtil.getId(mContext, "bb_register_confirm")) {
            if(!verifyCheckBox()){
                return;
            }
            startRegisterRequest();
        } else if (vid == ResUtil.getId(mContext, "bb_register_cancle")) {
            activityMgr.NewpopViewFromStack();
            activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "bb_code_send")) {
            doSendCodeRequest();
        } else if (vid == ResUtil.getId(mContext, "guild_callcustom")) {
            activityMgr.popViewFromStack();
            activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "guild_certification")) {
            activityMgr.NewpopViewFromStack();
            activityMgr.pushViewToStack(new QuickRegisterView(ownerActivity, activityMgr));
        }
    }
    
    @Override
    public void stopSyncTask(boolean stop) {
        if (registerAsyncTask != null) {
            registerAsyncTask.cancel(stop);
        }
    }
    
    // 发送验证
    public void doSendCodeRequest() {
        final String username = bb_user_txt.getText().toString().trim();
        final String uPhone = bb_mobile_txt.getText().toString().trim();
        originalPassword = bb_password_txt.getText().toString().trim();
        String user_rst = Checker.checkUsername(username, this.getContext());
        if (!user_rst.equals(Checker.IS_OK)) {
            Toast.makeText(getContext(), TipMessSingle.four_usernil, Toast.LENGTH_LONG).show();
            return;
            
        }
        String pass_rst = Checker.checkPassword(originalPassword, this.getContext());
        if (!pass_rst.equals(Checker.IS_OK)) {
            Toast.makeText(getContext(), TipMessSingle.five_passnil, Toast.LENGTH_LONG).show();
            return;
        }
        
        String mobile_format = Checker.checkPhoneNumber(uPhone, mContext);
        if (!mobile_format.equals(Checker.IS_OK)) {
            Toast.makeText(mContext, TipMessSingle.five_mobilenil, Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
            return;
        }
        
        final Map<String, String> tempMap = GuildBaseInfo.getInstance().getSmscodeParamsWithPassGuide(
            getContext(), uPhone, "send_phone_verify");
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        registerPhoneAsyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(tempMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                Log.e("getCodeResult", "getCodeResult" + rst);
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject msgjson = new JSONObject(msg);
                    Toast.makeText(mContext, "获取成功，验证码有效时间为1小时",
                        Toast.LENGTH_LONG).show();
                    Log.e("bindphonemustsmscode", "bindphonemustsmscode"
                        + msgjson.optString("code"));
                    
                    mSendMess.setEnabled(false);
                    timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        int i = 55;
                        
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = i--;
                            handler.sendMessage(msg);
                        }
                    };
                    timer.schedule(timerTask, 0, 1000);
                } catch (JSONException e) {
                    Toast.makeText(mContext, "注册已达到上限", Toast.LENGTH_LONG)
                        .show();
                    Log.d("BindPhone", "registed phone returns error msg");
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        
        registerPhoneAsyncTask.execute();
    }
    
    // 提交注册
    public void startRegisterRequest() {
        final String username = bb_user_txt.getText().toString().trim();
        final String mobile = bb_mobile_txt.getText().toString().trim();
        final String code = bb_mess_code.getText().toString().trim();
        originalPassword = bb_password_txt.getText().toString().trim();
        
        String user_rst = Checker.checkUsername(username, this.getContext());
        if (!user_rst.equals(Checker.IS_OK)) {
            Toast.makeText(getContext(), TipMessSingle.four_usernil,
                Toast.LENGTH_LONG).show();
            return;
            
        }
        String pass_rst = Checker.checkPassword(originalPassword, this.getContext());
        if (!pass_rst.equals(Checker.IS_OK)) {
            Toast.makeText(getContext(), TipMessSingle.five_passnil,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(mContext, TipMessSingle.five_codenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        final Map<String, String> tempMap = GuildBaseInfo.getInstance().getQuickRegisterParamsGuild(
            getContext(), mobile, originalPassword, code,
            "register", username);
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        registerPhoneAsyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(tempMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    Log.e("regisrst", "regisrst" + rst);
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG)
                            .show();
                        return;
                    }
                    
                    String msg = json.optString("data");
                    if (TextUtils.isEmpty(msg)) {
                        return;
                    }
                    JSONObject msgJson = new JSONObject(msg);
                    
                    String user_id = msgJson.optString("id");
                    String username = msgJson.optString("name");
                    String token = msgJson.optString("ticket");
                    
                    String bindState = msgJson.getString("pop_reg_phone");
                    save_intauthenticate = Integer.parseInt(msgJson.optString("pop_reg_idcard"));
    
                    if (msgJson.optString("game_discount") != null) {
                        String discount = msgJson.getString("game_discount");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                    }else {
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                    }
                    
                    DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
                    s_acct.auto_login = 1;
                    s_acct.user_name = username;
                    s_acct.user_password = originalPassword;
                    s_acct.is_valid = AccountHelper.ACCOUNT_VALID;
                    s_acct.user_id = user_id;
                    
                    Local_Account local_acct = new Local_Account();
                    local_acct.username = username;
                    local_acct.password = originalPassword;
                    local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                    AccountHelper.updateLocalAccounts(local_acct);
                    
                    if (dbHelper.isAccountPresent(s_acct)) {
                        dbHelper.updateAccount(s_acct);
                    } else {
                        dbHelper.insertNewAccount(s_acct);
                    }
                    QdLoginResult loginResult = new QdLoginResult(user_id,
                        username, token, "1", "0", "1");
                    
                    CommMessage.currentUserName = username;
                    CommMessage.currentPassword = originalPassword;
                    CommMessage.setRealType("register");
                    GuildBaseInfo.getInstance().SetLoginAuMess(username, originalPassword,
                        LoginSwitchManage.getInstance().result_authenticate + "");
                    GuildBaseInfo.setAcctsInfo(username, user_id, originalPassword);
                    
                    int gameState = CheckLoginStateUtil.getState(Integer.parseInt(bindState), save_intauthenticate);
                    boolean bindMust = false;
                    if (Integer.parseInt(bindState) == 2) {
                        bindMust = true;
                    }
                    switch (gameState) {
                        case 0:
                            CommMessage.setRealType("login");
                            activityMgr.notifyLoginSuccess(loginResult);
                            activityMgr.finishDialogOrActivity();
                            break;
                        case 1:
                        case 2:
                            activityMgr.pushViewToStack(new RealViewMust(ownerActivity, activityMgr));
                            break;
                        default:
                            activityMgr.pushViewToStack(new BindPhoneMustView(ownerActivity,
                                activityMgr, bindMust, loginResult, originalPassword, user_id));
                            break;
                    }
                    
                    FancyManager.getInstance().CallRegister(
                        QdRegisterCallback.SUCCEEDED,
                        QdRegisterCallback.BY_PHONE);
    
                    if (FancyManager.getInstance().isAdvertIdBool()) {
                        GameReportHelper.onEventRegister("register", true);
                    }
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        
        registerPhoneAsyncTask.execute();
    }
    
}
